// 登录模块控制器
class LoginController {
    constructor() {
        this.form = document.getElementById('loginForm');
        this.usernameInput = document.getElementById('username');
        this.passwordInput = document.getElementById('password');
        this.rememberMe = document.getElementById('rememberMe');
        this.loginBtn = document.getElementById('loginBtn');
        this.message = document.getElementById('message');
        
        this.init();
    }
    
    init() {
        // 绑定事件监听器
        this.bindEvents();
        
        // 检查是否有保存的用户名
        this.checkRememberedUser();
    }
    
    bindEvents() {
        // 表单提交事件
        this.form.addEventListener('submit', (e) => this.handleSubmit(e));
        
        // 实时验证
        this.usernameInput.addEventListener('input', () => this.validateUsername());
        this.passwordInput.addEventListener('input', () => this.validatePassword());
        
        // 输入框焦点事件
        this.usernameInput.addEventListener('focus', () => this.clearError('username'));
        this.passwordInput.addEventListener('focus', () => this.clearError('password'));
    }
    
    handleSubmit(e) {
        e.preventDefault();
        
        // 验证所有字段
        const isUsernameValid = this.validateUsername();
        const isPasswordValid = this.validatePassword();
        
        if (isUsernameValid && isPasswordValid) {
            this.performLogin();
        } else {
            this.showMessage('请正确填写所有字段', 'error');
        }
    }
    
    validateUsername() {
        const username = this.usernameInput.value.trim();
        const errorElement = document.getElementById('usernameError');
        
        if (!username) {
            this.setError('username', '用户名不能为空');
            return false;
        }
        
        if (username.length < 3) {
            this.setError('username', '用户名至少3个字符');
            return false;
        }
        
        if (!/^[a-zA-Z0-9_]+$/.test(username)) {
            this.setError('username', '用户名只能包含字母、数字和下划线');
            return false;
        }
        
        this.clearError('username');
        return true;
    }
    
    validatePassword() {
        const password = this.passwordInput.value;
        const errorElement = document.getElementById('passwordError');
        
        if (!password) {
            this.setError('password', '密码不能为空');
            return false;
        }
        
        if (password.length < 6) {
            this.setError('password', '密码至少6个字符');
            return false;
        }
        
        this.clearError('password');
        return true;
    }
    
    setError(field, message) {
        const errorElement = document.getElementById(field + 'Error');
        const inputElement = document.getElementById(field);
        
        errorElement.textContent = message;
        inputElement.classList.add('error');
    }
    
    clearError(field) {
        const errorElement = document.getElementById(field + 'Error');
        const inputElement = document.getElementById(field);
        
        errorElement.textContent = '';
        inputElement.classList.remove('error');
    }
    
    performLogin() {
        // 禁用登录按钮
        this.loginBtn.disabled = true;
        this.loginBtn.textContent = '登录中...';
        
        // 模拟登录请求
        setTimeout(() => {
            const username = this.usernameInput.value.trim();
            const password = this.passwordInput.value;
            
            // 模拟登录验证
            if (this.authenticate(username, password)) {
                // 记住用户名
                if (this.rememberMe.checked) {
                    localStorage.setItem('rememberedUsername', username);
                } else {
                    localStorage.removeItem('rememberedUsername');
                }
                
                this.showMessage('登录成功！正在跳转...', 'success');
                
                // 模拟跳转
                setTimeout(() => {
                    alert(`欢迎回来，${username}！`);
                    this.resetForm();
                }, 1500);
            } else {
                this.showMessage('用户名或密码错误', 'error');
                this.loginBtn.disabled = false;
                this.loginBtn.textContent = '登录';
            }
        }, 1000);
    }
    
    authenticate(username, password) {
        // 模拟用户数据库
        const users = [
            { username: 'admin', password: '123456' },
            { username: 'user', password: 'password' },
            { username: 'test', password: 'test123' }
        ];
        
        return users.some(user => 
            user.username === username && user.password === password
        );
    }
    
    checkRememberedUser() {
        const rememberedUsername = localStorage.getItem('rememberedUsername');
        if (rememberedUsername) {
            this.usernameInput.value = rememberedUsername;
            this.rememberMe.checked = true;
        }
    }
    
    showMessage(text, type) {
        this.message.textContent = text;
        this.message.className = `message ${type}`;
        
        // 3秒后自动隐藏消息
        setTimeout(() => {
            this.message.style.display = 'none';
        }, 3000);
    }
    
    resetForm() {
        this.form.reset();
        this.loginBtn.disabled = false;
        this.loginBtn.textContent = '登录';
        this.message.style.display = 'none';
        this.clearError('username');
        this.clearError('password');
    }
}

// 页面加载完成后初始化登录控制器
document.addEventListener('DOMContentLoaded', () => {
    new LoginController();
});

// 添加键盘事件支持
document.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
        const activeElement = document.activeElement;
        if (activeElement.tagName === 'INPUT') {
            document.getElementById('loginForm').dispatchEvent(new Event('submit'));
        }
    }
});